<?php
defined('SYSPATH') or die('No direct script access.');

class Model_Coupon extends Model_Base{
	
	protected $_table_name  = 'coupon';
	protected $_table_names_plural = false;
	
	public function insert($dataArray){
		$fileUtil = FileUtil::Factory();
		$result = $fileUtil->saveFilesForCoupon($this->defaultImgPath());
		if ($result != FALSE){
			$dataArray["smallpicture"] = $fileUtil->getFilePath($result["smallpicture"]);
			$dataArray["largepicture"] = $fileUtil->getFilePath($result["largepicture"]);
			$dataArray["createtime"] = Date::formatted_time();
			$dataArray["updatetime"] = Date::formatted_time();
			if($this->values($dataArray)->check()){
				return $this->save();
			}
		}
		return false;
	}
	
	public function update($dataArray){
		$fileUtil = FileUtil::Factory();
		$result = $fileUtil->saveFilesForCoupon($this->defaultImgPath());
		if ($result != FALSE){
			if (array_key_exists("smallpicture", $result) && $result['smallpicture'] != FALSE)
			{
				$result['smallpicture'] = $fileUtil->getFilePath($result["smallpicture"]);
				if ($result['smallpicture']!=$this->smallpicture){
					if (!empty($this->smallpicture)){
						$orginal_real_path = $this->defaultImgPath().DIRECTORY_SEPARATOR.$this->smallpicture;
						$fileUtil->deleteFile($orginal_real_path);
					}
					$this->smallpicture = $result['smallpicture'];
				}
			}
			if (array_key_exists("largepicture", $result) && $result['largepicture'] != FALSE)
			{
				$result['largepicture'] = $fileUtil->getFilePath($result["largepicture"]);
				if ($result['largepicture']!=$this->largepicture){
					if (!empty($this->largepicture)){
						$orginal_real_path = $this->defaultImgPath().DIRECTORY_SEPARATOR.$this->largepicture;
						$fileUtil->deleteFile($orginal_real_path);
					}
					$this->largepicture = $result['largepicture'];
				}
			}
		}
		$this->group=$dataArray["group"];
		$this->sort=$dataArray["sort"];
		$this->desc=$dataArray["desc"];
		$this->height=$dataArray["height"];
		$this->width=$dataArray["width"];
		$this->updatetime=Date::formatted_time();

		return $this->save();
	}
	
	protected function modelWithCondition($filters){
		$model = $this->where("status","=","A");
		if (array_key_exists("group", $filters)){
			$model = $this->and_where("group","=",$filters["group"]);
		}
		return $model->order_by("sort","ASC")->order_by("createtime","DESC");
	}
	
	private function defaultImgPath(){
		return $_SERVER["DOCUMENT_ROOT"].DIRECTORY_SEPARATOR.Upload::$default_directory.DIRECTORY_SEPARATOR.'coupon';
	}
}